package com.yang.ddd.domain.space.service.impl;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yang.ddd.domain.space.entity.Space;
import com.yang.ddd.domain.space.entity.SpaceLevel;
import com.yang.ddd.domain.space.repository.SpaceRepository;
import com.yang.ddd.domain.space.service.SpaceDomainService;
import com.yang.ddd.domain.space.valueobject.SpaceLevelEnum;
import com.yang.ddd.interfaces.dto.space.SpaceQueryRequest;
import com.yang.ddd.interfaces.vo.space.SpaceVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author Young
 * @description 针对表【picture(图片)】的数据库操作Service实现
 * @createDate 2025-03-25 23:25:31
 */
@Service
@Slf4j
public class SpaceDomainServiceImpl implements SpaceDomainService {

    @Resource
    private SpaceRepository spaceRepository;


    @Override
    public Wrapper<Space> getQueryWrapper(SpaceQueryRequest spaceQueryRequest) {
        QueryWrapper<Space> queryWrapper = new QueryWrapper<>();
        if (spaceQueryRequest == null) {
            return queryWrapper;
        }
        // 从对象中取值
        Long id = spaceQueryRequest.getId();
        Long userId = spaceQueryRequest.getUserId();
        String spaceName = spaceQueryRequest.getSpaceName();
        Integer spaceLevel = spaceQueryRequest.getSpaceLevel();
        String sortField = spaceQueryRequest.getSortField();
        String sortOrder = spaceQueryRequest.getSortOrder();
        Integer spaceType = spaceQueryRequest.getSpaceType();

        queryWrapper.eq(ObjUtil.isNotEmpty(spaceType), "spaceType", spaceType);
        queryWrapper.eq(ObjUtil.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjUtil.isNotEmpty(userId), "userId", userId);
        queryWrapper.like(StrUtil.isNotBlank(spaceName), "spaceName", spaceName);
        queryWrapper.eq(ObjUtil.isNotEmpty(spaceLevel), "spaceLevel", spaceLevel);
        // 排序
        queryWrapper.orderBy(StrUtil.isNotBlank(sortField), sortOrder.equals("ascend"), sortField);
        return queryWrapper;
    }


    @Override
    public boolean save(Space space) {
        return spaceRepository.save(space);
    }

    @Override
    public boolean isExists(Long userId, Integer spaceType) {
        return spaceRepository.lambdaQuery()
                .eq(Space::getUserId, userId)
                .eq(Space::getSpaceType, spaceType)
                .exists();
    }

    @Override
    public Space getById(Long spaceId) {
        return spaceRepository.getById(spaceId);
    }

    @Override
    public List<Space> list(QueryWrapper<Space> queryWrapper) {
        return spaceRepository.list(queryWrapper);
    }

    @Override
    public List<Space> listByIds(Set<Long> spaceIdSet) {
        return spaceRepository.listByIds(spaceIdSet);
    }

    /**
     * @param finalSpaceId 空间id
     * @param picSize      更新大小
     * @param b            true：消耗额度空间 false：增加额度空间
     * @return
     */
    @Override
    public boolean updateQuota(Long finalSpaceId, Long picSize, boolean b) {
        if (b) {
            return spaceRepository.lambdaUpdate()
                    .eq(Space::getId, finalSpaceId)
                    .setSql("totalSize = totalSize + " + picSize)
                    .setSql("totalCount = totalCount + 1")
                    .update();
        }
        return spaceRepository.lambdaUpdate()
                .eq(Space::getId, finalSpaceId)
                .setSql("totalSize = totalSize - " + picSize)
                .setSql("totalCount = totalCount - 1")
                .update();
    }
    public Page<SpaceVO> getSpaceVO(Page<Space> spacePage) {
        List<Space> records = spacePage.getRecords();
        Page<SpaceVO> result = new Page<>(spacePage.getCurrent(), spacePage.getPages(), spacePage.getTotal());
        if (CollUtil.isEmpty(records)) {
            return result;
        }
        List<SpaceVO> collect = records.stream().map(SpaceVO::objToVo).collect(Collectors.toList());
        result.setRecords(collect);
        return result;
    }

    @Override
    public Page<Space> listSpaceByPage(SpaceQueryRequest spaceQueryRequest) {
        long current = spaceQueryRequest.getCurrent();
        long size = spaceQueryRequest.getPageSize();
        // 查询数据库
        return spaceRepository.page(new Page<>(current, size),
                this.getQueryWrapper(spaceQueryRequest));
    }

    @Override
    public Page<SpaceVO> listSpaceVOByPage(SpaceQueryRequest spaceQueryRequest) {
        Page<Space> spacePage = this.listSpaceByPage(spaceQueryRequest);
        return this.getSpaceVO(spacePage);
    }

    @Override
    public List<SpaceLevel> listSpaceLevel() {
        return Arrays.stream(SpaceLevelEnum.values()) // 获取所有枚举
                .map(spaceLevelEnum -> new SpaceLevel(
                        spaceLevelEnum.getValue(),
                        spaceLevelEnum.getText(),
                        spaceLevelEnum.getMaxCount(),
                        spaceLevelEnum.getMaxSize()))
                .collect(Collectors.toList());
    }

    @Override
    public Boolean removeById(long id) {
        return spaceRepository.removeById(id);
    }

    @Override
    public boolean updateById(Space space) {
        return spaceRepository.updateById(space);
    }

}







